package com.jiyun.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiyun.mapper.DeptMapper;
import com.jiyun.mapper.EmpMapper;
import com.jiyun.pojo.Dept;
import com.jiyun.pojo.Emp;
import com.jiyun.pojo.EmpDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmpService {

    @Autowired
    DeptMapper deptMapper;
    @Autowired
    EmpMapper empMapper;

    public Page findPage(Integer pageNum, Integer pageSize, EmpDTO empDTO) {
        // 要想分页能用，必须创建拦截器
        Page<Emp> page = new Page<>(pageNum,pageSize);
        // 1.一框多查   name  -》 name，sex，hobby   select * from xx where name like xx or sex = xx or hobby= xx
        LambdaQueryWrapper<Emp> qw = new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotBlank(empDTO.getName()),Emp::getName,empDTO.getName());
        qw.or();
        if(StringUtils.isNotBlank(empDTO.getName())) {
            if(empDTO.getName().equals("男")){
                qw.eq(Emp::getSex,  "0" );
            }
            if(empDTO.getName().equals("女")){
                qw.eq(Emp::getSex,  "1" );
            }
        }
        qw.or();
        qw.like(StringUtils.isNotBlank(empDTO.getName()),Emp::getHobby,empDTO.getName());
        // 2.部门id查询
        qw.eq(empDTO.getDeptId()!=null,Emp::getDeptId,empDTO.getDeptId());
        // 3.生日区间查询
        qw.ge(empDTO.getDate1()!=null,Emp::getBirthday,empDTO.getDate1());
        qw.le(empDTO.getDate2()!=null,Emp::getBirthday,empDTO.getDate2());

        empMapper.selectPage(page,qw);

        // 单独将数据取出，并根据数据的id，去得到部门信息
        for (Emp emp : page.getRecords()) {
            Dept dept = deptMapper.selectById(emp.getDeptId());
            emp.setDept(dept);
        }
        return page;
    }

    public List<Dept> deptList() {
        return deptMapper.selectList(null);
    }

    public void add(Emp emp) {
        empMapper.insert(emp);
    }

    public Emp findById(Integer id) {
        return empMapper.selectById(id);
    }

    public void update(Emp emp) {
        empMapper.updateById(emp);
    }

    public void deleteOne(Integer id) {
        empMapper.deleteById(id);
    }

    public List<Emp> findAll() {
        List<Emp> list = empMapper.selectList(null);
        for (Emp emp : list) {
            Dept dept = deptMapper.selectById(emp.getDeptId());
            emp.setDept(dept);
        }
        return list;
    }

    public Dept findByName(String name) {
        LambdaQueryWrapper<Dept> qw = new LambdaQueryWrapper<>();
        qw.eq(Dept::getName,name);
        return deptMapper.selectOne(qw);
    }

    public void addAll(List<Emp> list) {
        for (Emp emp : list) {
            empMapper.insert(emp);
        }
    }
}
